<?php

class Gallery_Model_Tags extends Kernel_Model
{

	/**
	 * Set tags (do not replace existing ones)
	 *
	 * @param array $tags
	 */
	public function setTags($tags)
	{
		$values = array();
		foreach ($tags as $tag) {
			$values[] = array($tag);
		}
		
		database::insertValues('photo_tags', array('name'), $values, true);
	}

	/**
	 * Return tags by their names
	 *
	 * @param array $tags_names
	 * @return array
	 */
	public function getTagsByNames(array $tags_names)
	{
		return $this->_getTags($tags_names);
	}

	public function getTags()
	{
		return $this->_getTags();
	}

	/**
	 * Return tag cloud
	 *
	 * @param string $type
	 * @return Zend_Tag_Cloud
	 */
	public function getTagCloud($type)
	{
		if (!in_array($type, Tag_Utils::getTypes())) {
			trigger_error('Unknow cloud type given', E_USER_ERROR);
		}

		$options = get_array_element(Kernel_Config::get('tag', 'options'), $type);

		$query = '
			SELECT
					*
			FROM
					(SELECT
							`p_t`.`id`,
							`p_t`.`name`,
							(SELECT COUNT(*) FROM `photos_2_tags` WHERE `tag_id` = `p_t`.`id`) `weight`
					FROM
							`photo_tags` `p_t`
					HAVING
							`weight` > 0
					ORDER BY
							`weight` DESC, `p_t`.`name` ASC
					LIMIT
							' . $options['limit'] . ') `tags`
			ORDER BY
					`tags`.`name` ASC
		';

		$cloud = new Zend_Tag_Cloud;
		$entries = database::fetchAll($query);

		foreach ($entries as $entry) {
            $cloud->appendTag(array(
                'title' => htmlspecialchars($entry['name']),
                'weight' => $entry['weight'],
                'params' => array('url' => 'tag/' . $entry['id'] . '.html'),
                ));
        }


        $cloud->getCloudDecorator()->setHtmlTags(array('div'));
        $cloud
            ->getTagDecorator()
            ->setMinFontSize($options['min_font_size'])
            ->setMaxFontSize($options['max_font_size'])
            ->setHtmlTags(array('span'))
        ;

		return $cloud;
	}

	private function _getTags(array $tags_names = null)
	{
		$query = '
			SELECT
					`id`, 
					`name`
			FROM
					`photo_tags`
		';
		if (!is_null($tags_names)) {
			$query .= '
				WHERE
						' . database::values(array('name' => $tags_names)) . '
			';
		}
		$query .= '
			ORDER BY
					`name` ASC
		';
		
		return database::fetchPairs($query);
	}

	/**
	 * Return self instance
	 *
	 * @return Gallery_Model_Tags
	 */
	static public function getInstance()
	{
		return new self;
	}

}